<template>
  <el-cascader
      v-model="value"
      :options="options"
      :props = "props"
      @change="handleChange"
      :disabled="prop.disabled"
      clearable
  />
</template>

<script setup>
import {getGeos} from "@/plugin/geo/api/geo";
import {onMounted, ref} from "vue";

const prop = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  province: {
    type: String,
    default: ''
  },
  city: {
    type: String,
    default: ''
  },
  area: {
    type: String,
    default: ''
  },
})

const emits = defineEmits(['update:province', 'update:city', 'update:area'])


const options = ref([])
const value = ref([])
const props = ref({
  lazy: true,
  lazyLoad :async (node,resolve)=>{
    loadMap.set(node.code, { node, resolve })
    const data = node.data
    resolve(await getTreeData(data.level, data.code||0) || [])
  },
  label: 'name',
  value: 'code',
})

const getTreeData = async(level, code) => {
  const res = await getGeos({ level, code })
  if (level === 1) {
    console.log(res)
    res.data.forEach(element => {
      element.leaf = true
    })
  }
  return res.data
}

const handleChange = (value,e) =>{
  if(value){
    emits('update:province', value[0])
    emits('update:city', value[1])
    emits('update:area', value[2])
    return
  }
  emits('update:province', '')
  emits('update:city', '')
  emits('update:area', '')
}

const loadMap = new Map()

onMounted(()=>{
  value.value = [prop.province, prop.city, prop.area]
})

</script>
